import { createVNode, render } from 'vue'
import Message from './Message.vue'

// 消息实例列表
const instances: any[] = []
let seed = 1

// 创建消息容器
let messageContainer: HTMLElement | null = null

// 获取或创建消息容器
function getMessageContainer() {
  if (messageContainer)
    return messageContainer

  messageContainer = document.createElement('div')
  messageContainer.className = 'message-container-wrapper'
  messageContainer.style.position = 'fixed'
  messageContainer.style.top = '20px'
  messageContainer.style.left = '50%'
  messageContainer.style.transform = 'translateX(-50%)'
  messageContainer.style.display = 'flex'
  messageContainer.style.flexDirection = 'column'
  messageContainer.style.alignItems = 'center'
  messageContainer.style.gap = '16px'
  messageContainer.style.zIndex = '9999'
  document.body.appendChild(messageContainer)

  return messageContainer
}

// 消息配置接口
export interface MessageOptions {
  type?: 'success' | 'error' | 'info'
  message: string
  duration?: number
  onClose?: () => void
}

// 创建消息实例
function createMessage(options: MessageOptions) {
  // 创建容器
  const id = `message_${seed++}`
  const container = document.createElement('div')
  container.setAttribute('class', 'message-item')
  container.setAttribute('id', id)

  // 处理关闭回调
  const userOnClose = options.onClose
  const opts = {
    ...options,
    onClose: () => {
      closeMessage(id, userOnClose)
    },
  }

  // 创建VNode
  const vnode = createVNode(Message, opts)

  // 获取父容器
  const parent = getMessageContainer()

  // 渲染到容器
  render(vnode, container)
  parent.appendChild(container)

  // 保存实例
  const instance = {
    id,
    vnode,
    options: opts,
    container,
  }

  instances.push(instance)

  return instance
}

// 关闭消息
function closeMessage(id: string, userOnClose?: () => void) {
  const index = instances.findIndex(instance => instance.id === id)
  if (index === -1)
    return

  const { container } = instances[index]
  userOnClose?.()

  // 移除DOM
  render(null, container)
  container.parentNode?.removeChild(container)

  // 移除实例
  instances.splice(index, 1)

  // 如果没有消息了，移除父容器
  if (instances.length === 0 && messageContainer && messageContainer.parentNode) {
    document.body.removeChild(messageContainer)
    messageContainer = null
  }
}

// 创建不同类型的消息方法
const message = {
  info(message: string, options: Omit<MessageOptions, 'message' | 'type'> = {}) {
    return createMessage({ message, type: 'info', ...options })
  },
  success(message: string, options: Omit<MessageOptions, 'message' | 'type'> = {}) {
    return createMessage({ message, type: 'success', ...options })
  },
  error(message: string, options: Omit<MessageOptions, 'message' | 'type'> = {}) {
    return createMessage({ message, type: 'error', ...options })
  },
}

export default message
